<template>
  <div ref="wrap"
       class="wrap">
    <div ref="content"
         class="dd_run_lamp_content"
         :class="animationClass"
         :style="contentStyle"
         @animationend="onAnimationEnd"
         @webkitAnimationEnd="onAnimationEnd">
      <!-- <slot></slot> -->
      <span>
        {{content}}
      </span>

    </div>
  </div>
</template>
<script lang="ts">
import { Vue, Component, Watch, Prop } from "vue-property-decorator";
// 每个组件必须加
@Component
export default class DdRunLamp extends Vue {
  wrapWidth: number = 0;
  firstRound: boolean = true;
  duration: number = 0; //css3一次动画需要的时间
  offsetWidth: number = 0; //子盒子的宽度
  animationClass: string = ""; //添加animate动画
  // 组件的数据
  @Prop({
    type: String,
    default: "ddelement致力于能够做出较为方便和应用多场景的组件库"
  })
  content!: string;

  @Prop({
    type: Number,
    default: 0.5
  })
  delay!: number;

  @Prop({
    type: Number,
    default: 100
  })
  speed!: number;

  get contentStyle() {
    return {
      //第一次从头开始,第二次动画的时候需要从最右边出来所以宽度需要多出父盒子的宽度
      paddingLeft: (this.firstRound ? 0 : this.wrapWidth) + "px",
      //只有第一次的时候需要延迟
      animationDelay: (this.firstRound ? this.delay : 0) + "s",
      animationDuration: this.duration + "s"
    };
  }

  @Watch("content", { immediate: true })
  onContentChanged(val: string, oldVal: string) {
    // console.log(val, oldVal, "77777777777777777");
    this.$nextTick(() => {
      const { wrap, content } = this.$refs;
      const wrapWidth = (wrap as any).getBoundingClientRect().width;
      const offsetWidth = (content as any).getBoundingClientRect().width;
      this.wrapWidth = wrapWidth;
      this.offsetWidth = offsetWidth;
      this.duration = offsetWidth / this.speed;
      this.animationClass = "animate";
    });
  }

  //这个函数是第一次动画结束的时候,第一次没有使用infinite,第一次动画执行完成后开始使用添加animate-infinite动画
  onAnimationEnd() {
    this.firstRound = false;
    //这是时候样式多出了padding-left:this.wrapWidth;所以要想速度一样需要重新计算时间
    this.duration = (this.offsetWidth + this.wrapWidth) / this.speed;
    this.animationClass = "animate-infinite";
  }
}
</script>
<style scoped>
.wrap {
  width: 100%;
  height: 24px;
  overflow: hidden;
  position: relative;
  background: rgba(211, 125, 066, 1);
  position: relative;
  padding: 0;
}

.wrap .dd_run_lamp_content {
  position: absolute;
  white-space: nowrap;
}

.animate {
  animation: paomadeng linear;
}

.animate-infinite {
  animation: paomadeng-infinite linear infinite;
}

@keyframes paomadeng {
  to {
    transform: translate3d(-100%, 0, 0);
  }
}

@keyframes paomadeng-infinite {
  to {
    transform: translate3d(-100%, 0, 0);
  }
}
</style>
